from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework import mixins

from utils.permissions import IsOwnerOrReadOnly  # 自定义权限，收藏时判断是否是当前用户操作
from .models import ShoppingCart, OrderInfo, OrderGoods
from .serializers import ShopCartSerializer, ShopCartDetailSerializer, OrderSerializer, OrderDetailSerializer


class ShoppingCartViewSet(viewsets.ModelViewSet):
    """
    购物车功能
    list:
        获取购物车详情
    create:
        加入购物车
    delete:
        删除购物记录
    """
    permission_classes = (IsAuthenticated,
                          IsOwnerOrReadOnly)  # IsAuthenticated任何经过身份认证的用户，自定义IsOwnerOrReadOnly是否是当前用户操作，这里用于添加和取消收藏时判断是否为当前用户
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = ShopCartSerializer  # 添加商品到购物车
    lookup_field = "goods_id"

    # 重写perform_create()方法
    def perform_create(self, serializer):
        """添加购物车后扣减商品库存"""
        shop_cart = serializer.save()
        goods = shop_cart.goods
        if shop_cart.nums_news:  # 商品已添加到购物车,追加商品到购物车扣减库存
            goods.goods_num -= shop_cart.nums_news
        else:  # 场景1：购物车为空时添加商品，扣减商品库存
            goods.goods_num -= shop_cart.nums
        goods.save()

    # 重写perform_destroy()方法，删除购物车中商品时,商品库存数量加回去
    def perform_destroy(self, instance):
        goods = instance.goods
        goods.goods_num += instance.nums
        goods.save()
        instance.delete()

    # 重写perform_update()修改购物车数量后，更新库存
    def perform_update(self, serializer):
        existed_record = ShoppingCart.objects.get(id=serializer.instance.id)  # 获取已有的值
        existed_nums = existed_record.nums  # 之前保存时的值
        saved_record = serializer.save()  # 保存之后的值
        nums = saved_record.nums - existed_nums  # 修改后的数量 - 修改前的数量 = 变化的数量
        # nums大于0说明又购买了商品
        goods = saved_record.goods
        goods.goods_num -= nums
        goods.save()

    def get_serializer_class(self, *args, **kwargs):
        if self.action == "list":
            return ShopCartDetailSerializer
        else:
            return ShopCartSerializer

    def get_queryset(self):
        return ShoppingCart.objects.filter(user=self.request.user)


class OrderViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,
                   viewsets.GenericViewSet):
    """
    订单管理
    list:
        获取个人订单
    delete:
        删除订单
    create:
        新增订单
    """
    permission_classes = (IsAuthenticated,
                          IsOwnerOrReadOnly)  # IsAuthenticated任何经过身份认证的用户，自定义IsOwnerOrReadOnly是否是当前用户操作，这里用于添加和取消收藏时判断是否为当前用户
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    serializer_class = OrderSerializer

    # 第一步：将购物车中商品数据添加到订单列表，第二步：清空购物者
    def get_queryset(self):
        return OrderInfo.objects.filter(user=self.request.user)  # 当前用户的订单

    def get_serializer_class(self):
        if self.action == "retrieve":  # 查询详情
            return OrderDetailSerializer
        return OrderSerializer

    def perform_create(self, serializer):
        order = serializer.save()
        shop_carts = ShoppingCart.objects.filter(user=self.request.user)
        for shop_cart in shop_carts:
            order_goods = OrderGoods()
            order_goods.goods = shop_cart.goods
            order_goods.goods_num = shop_cart.nums
            order_goods.order = order
            order_goods.save()
            shop_cart.delete()  # 清空购物车
        return order
